#!/bin/sh
# toughradius docker install script
# author: jamiesun.net@gmail.com
# version: 0.0.17

set -e

install()
{
    pypy -m pip install https://github.com/talkincode/toughlib/archive/master.zip --upgrade --no-deps
    pypy -m pip install https://github.com/talkincode/txradius/archive/master.zip --upgrade --no-deps

    git clone -b stable_v2 https://github.com/talkincode/ToughRADIUS.git /opt/toughradius

    cp /opt/toughradius/etc/toughradius.json /etc/toughradius.json
    cp /opt/toughradius/etc/supervisord.conf /etc/supervisord.conf

    chmod +x /opt/toughradius/toughctl
}

initserv()
{
    if [ ! -f "/var/toughradius/data" ];then
        mkdir -p /var/toughradius/data
    fi

    if [ ! -f "/var/toughradius/.install" ];then
        pypy /opt/toughradius/toughctl --initdb
        echo "ok" > /var/toughradius/.install
        echo "init database ok!"
    fi

    echo "init service ok!"
}

standalone()
{
    initserv
    pypy /opt/toughradius/toughctl --standalone
}

manage()
{
    initserv
    pypy /opt/toughradius/toughctl --manage
}

auth()
{
    initserv
    pypy /opt/toughradius/toughctl --auth
}

acct()
{
    initserv
    pypy /opt/toughradius/toughctl --acct
}

task()
{
    pypy /opt/toughradius/toughctl --task
}

worker()
{
    pypy /opt/toughradius/toughctl --worker
}

upgrade()
{
    cd /opt/toughradius
    git fetch origin stable_v2
    git reset --hard FETCH_HEAD
    git clean -df
}

upgrade_dev()
{
    cd /opt/toughradius
    git fetch origin master
    git reset --hard FETCH_HEAD
    git clean -df
}


uplib()
{
    pypy -m pip install https://github.com/talkincode/toughlib/archive/master.zip --upgrade --no-deps
    pypy -m pip install https://github.com/talkincode/txradius/archive/master.zip --upgrade --no-deps
}

case "$1" in

  install)
    install
  ;;

  initserv)
    initserv
  ;;

  standalone)
    standalone
  ;;

  manage)
    manage
  ;;

  auth)
    auth
  ;;

  acct)
    acct
  ;;

  task)
    task
  ;;

  worker)
    worker
  ;;

  upgrade)
    upgrade
  ;;

  upgrade_dev)
    upgrade_dev
  ;;

  uplib)
    uplib
  ;;

esac

